package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import model.HojaProduccion;
import model.ProduccionBase;
import model.Pudin;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import tables.PedidosTableModel;
import db.LocalDatabase;



public class PudinesPanel extends JPanel implements ActionListener, TableModelListener {

	ArrayList<JTable> jt;
	ArrayList<PedidosTableModel> ptm;
	JScrollPane jsp;
	ArrayList<ProduccionBase> produccionlist;
	ProduccionBase.TipoBase tipoBase;
	String baseSabor;
	JComboBox sabores;
	int choice = 0;
	int progress;
	DateTime dia;
	ArrayList<ArrayList<Integer>> pesos;
	Integer pesototal;
	JButton produccion,guardar;
	LocalDatabase localDB;
	
	PudinesPanel(JFrame parent, ProduccionBase.TipoBase tipoBase, int progress, DateTime dia) {
		this.dia = dia;
		this.progress = progress;
		this.setLayout(new BorderLayout());
		this.tipoBase = tipoBase;
		this.baseSabor = tipoBase.name();
		localDB = new LocalDatabase();
		pesos = new ArrayList<ArrayList<Integer>>();
		
	}
	
	public void init() {
		if(tipoBase.name().equals("Vainilla")) {
			sabores = new JComboBox(Pudin.BaseSabor.getVainilla());
		}
		else if(tipoBase.name().equals("Chocolate")) {
			sabores = new JComboBox(Pudin.BaseSabor.getChocolate());
		}
		else if(tipoBase.name().equals("Postre")) {
			sabores = new JComboBox(Pudin.BaseSabor.getPostre());
		}
		else if(tipoBase.name().equals("Pie")) {
			sabores = new JComboBox(Pudin.BaseSabor.getPie());
		}
		else if(tipoBase.name().equals("Helado")) {
			sabores = new JComboBox(Pudin.BaseSabor.getHelado());
		}
		//sabores.setSelectedIndex(0);
		
		sabores.setMaximumSize(new Dimension(25,30));
		
		
		produccionlist = new ArrayList<ProduccionBase>();
		jt = new ArrayList<JTable>();
		ptm = new ArrayList<PedidosTableModel>();
		
		for(int i=0; i<sabores.getItemCount();i++) {
			pesos.add(new ArrayList<Integer>());
			produccionlist.add(new ProduccionBase(this.tipoBase,sabores.getItemAt(i).toString(),dia));
			ptm.add(new PedidosTableModel());
			ArrayList<ArrayList<Object>> lista = produccionlist.get(i).getPedidos();
			for(int j = 0; j< lista.size(); j++) {		
				pesos.get(i).add((Integer) lista.get(j).get(lista.get(j).size()-1));
			}
			ptm.get(i).updateTable(produccionlist.get(i).getPedidos());
			jt.add(new JTable(ptm.get(i)));
			jt.get(i).setRowHeight(22);
			jt.get(i).getTableHeader().setResizingAllowed(false);
			jt.get(i).getTableHeader().setReorderingAllowed(false);
			jt.get(i).getTableHeader().setFont(new Font("Dialog", Font.BOLD, 12));
			jt.get(i).setFont(new Font("Courier New", Font.TRUETYPE_FONT, 12));
			progress++;
		}
		
		
		createTable();
		setColumnWidth(0);
		createMainPanel(baseSabor);
		
		sabores.addActionListener(this);
	}
	
	public void createTable() {

		jsp = new JScrollPane(jt.get(sabores.getSelectedIndex()));
	}
	
	public JPanel createLowerPanel() {
		
		URL imgURL = ClassLoader.getSystemResource("images/pdf.png");
		Image image = Toolkit.getDefaultToolkit().getImage(imgURL);


		ImageIcon pdficon = new ImageIcon(image);

		Image img = pdficon.getImage();  
		Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		pdficon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/database.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);


		ImageIcon saveicon = new ImageIcon(image);

		img = saveicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		saveicon = new ImageIcon(newimg);
		
		JPanel lowerPanel = new JPanel();
		lowerPanel.setLayout(new BoxLayout(lowerPanel, BoxLayout.X_AXIS));
		lowerPanel.add(Box.createHorizontalGlue());
		
		guardar = new JButton("Guardar",saveicon);
		guardar.addActionListener(this);
		guardar.setActionCommand("guardar");
		lowerPanel.add(guardar);
		
		produccion = new JButton("Hoja de Produccion",pdficon);
		produccion.addActionListener(this);
		produccion.setActionCommand("produccion");
		lowerPanel.add(produccion);
		
		lowerPanel.add(Box.createHorizontalGlue());
		
		return lowerPanel;
	}
	
	public JPanel createUpperPanel() {
		
		JPanel upperPanel = new JPanel();
		upperPanel.setLayout(new BoxLayout(upperPanel, BoxLayout.X_AXIS));
		JLabel saborLabel = new JLabel("Fecha: " + dia.toLocalDate() + " | Base: " + tipoBase.name() + " | Sabor: " + baseSabor); 
		upperPanel.add(saborLabel);
		upperPanel.add(Box.createHorizontalGlue());
		
		sabores.setSelectedIndex(choice);
		
		
		upperPanel.add(sabores);
		//upperPanel.add(new JButton("mostrar"));
		//upperPanel.add(Box.createHorizontalGlue());
		
		return upperPanel;
	}
	
	public void updateTable() {
		//ptm.updateTable(produccionlist.get(sabores.getSelectedIndex()).getPedidos());
	}
	
	public void createMainPanel(String baseSabor) {
		this.removeAll();
		this.baseSabor = baseSabor;
				
		createTable();
		setColumnWidth(sabores.getSelectedIndex());
		
		JPanel centerPanel = new JPanel(new BorderLayout());
		
		centerPanel.add(jsp,BorderLayout.CENTER);
		centerPanel.add(createUpperPanel(),BorderLayout.NORTH);
		
		this.add(centerPanel,BorderLayout.CENTER);
		this.add(createLowerPanel(),BorderLayout.SOUTH);
		
		this.validate();
		this.repaint();
	}
	
	private void setColumnWidth(int index) {

			jt.get(index).setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			jt.get(index).getColumnModel().getColumn(0).setPreferredWidth(150);
			jt.get(index).getColumnModel().getColumn(1).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(2).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(3).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(4).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(5).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(6).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(7).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(8).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(9).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(10).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(11).setPreferredWidth(80);
			jt.get(index).getColumnModel().getColumn(12).setPreferredWidth(96);
			
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		if(arg0.getActionCommand().equals("comboBoxChanged")) {
			JComboBox combo = (JComboBox) arg0.getSource();
			String basesabor;
			choice = combo.getSelectedIndex();
			if(tipoBase.name().equals("Vainilla")) {
				baseSabor = Pudin.BaseSabor.values()[combo.getSelectedIndex()+Pudin.BaseSabor.getVainillaIndex()].sabor();
			}
			else if(tipoBase.name().equals("Chocolate")) {
				baseSabor = Pudin.BaseSabor.values()[combo.getSelectedIndex()+Pudin.BaseSabor.getChocolateIndex()].sabor();
			}
			else if(tipoBase.name().equals("Postre")) {
				baseSabor = Pudin.BaseSabor.values()[combo.getSelectedIndex()+Pudin.BaseSabor.getPostreIndex()].sabor();
			}
			else if(tipoBase.name().equals("Pie")) {
				baseSabor = Pudin.BaseSabor.values()[combo.getSelectedIndex()+Pudin.BaseSabor.getPieIndex()].sabor();
			}
			else if(tipoBase.name().equals("Helado")) {
				baseSabor = Pudin.BaseSabor.values()[combo.getSelectedIndex()+Pudin.BaseSabor.getHeladoIndex()].sabor();
			}
			createMainPanel(baseSabor);
		}
		
		else if(arg0.getActionCommand().equals("produccion")) {
			
			JFileChooser fc = new JFileChooser();
			int returnVal = fc.showDialog(this, "Guardar");
			
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				   File file = fc.getSelectedFile();
				   HojaProduccion hojaDeProduccion = new HojaProduccion();
				   hojaDeProduccion.crearHoja(file,sabores,jt,dia,tipoBase,getPesoTotal(),getPesoList());
				} 
		}
		
		else if(arg0.getActionCommand().equals("guardar")) {
			JTable table = jt.get(sabores.getSelectedIndex());
			 DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy");
			 String str = fmt.print(dia);
			for(int i=0;i<table.getRowCount();i++) {
				localDB.insertInventarioAdelanto((String) sabores.getSelectedItem(), (String) table.getValueAt(i, 0), 
						Integer.valueOf( (String) table.getValueAt(i, 10)), Integer.valueOf( (String) table.getValueAt(i, 11)),
						dia, localDB.getCodigos(tipoBase, sabores.getSelectedItem().toString()).get(i));
			}
		}
		
	}

	@Override
	public void tableChanged(TableModelEvent arg0) {
		this.validate();
		this.repaint();
	}
	
	public int getProgress() {
		return progress;
	}
	
	public void setProgress(int progress) {
		this.progress = progress;
	}
	
	public int getPesoTotal() {
		int total = 0;
		for(int i=0;i<jt.size();i++) {
			for(int j=0;j<jt.get(i).getRowCount();j++) {
				total += (Integer.valueOf((String) jt.get(i).getValueAt(j, 12)) * pesos.get(i).get(j));
			}
		}
		return total;
	}
	
	public ArrayList<Integer> getPesoList() {
		ArrayList<Integer> pesoList = new ArrayList<Integer>();
		
		for(int i=0;i<jt.size();i++) {
			pesoList.add(0);
			for(int j=0;j<jt.get(i).getRowCount();j++) {
				pesoList.set(i, pesoList.get(i) + (Integer.valueOf((String) jt.get(i).getValueAt(j, 12)) * pesos.get(i).get(j)));
			}
		}
		return pesoList;
	}
	
	public ArrayList<JTable> getTable() {
		return jt;
	}
}
